﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections.Specialized;

namespace Transcend.FileUploader.Utility
{
    public class SimpleStringLayout
    {

        private Regex regexPattern = null;

        private string pattern;
        /// <summary>
        /// 解析正则
        /// </summary>
        public string Pattern
        {
            get { return pattern; }
            set { pattern = value; }
        }

        private HybridDictionary layout;
        /// <summary>
        /// 键-值映射器
        /// </summary>
        public HybridDictionary Layout
        {
            get { return layout; }
            set { layout = value; }
        }

        public SimpleStringLayout(string parsePattern)
        {
            this.pattern = parsePattern;
            regexPattern = new Regex(parsePattern, RegexOptions.IgnoreCase);
        }

        /// <summary>
        /// 仅取第一次匹配成功的值
        /// </summary>
        public string resolve(string target, string part)
        {

            int partIndex = -1;
            Match m = null;

            string partVal = null;

			if (layout == null || string.IsNullOrEmpty(target) || string.IsNullOrEmpty(part))
            {
                return partVal;
            }
            partIndex = ConvertHelper.ToInt32(layout[part], -1);
            if (partIndex > -1)
            {
                m = regexPattern.Match(target);

                if (m.Success && partIndex <= m.Groups.Count)
                {
                    partVal = m.Groups[partIndex].Value;
                }
            }
            return partVal;
        }

    }
}
